import sys
import time
import mysql.connector
import threading
# from followth_crawl import pool,getconn
import mysql.connector
from MySQLHelper_xue import MySQLHelper_xue
from mysql.connector import pooling
import traceback
import logging

def get_disk_serial_simple():
    """获取第一个硬盘序列号（简化版）"""
    try:
        import wmi
        c = wmi.WMI()
        for disk in c.Win32_DiskDrive():
            if disk.SerialNumber:
                return disk.SerialNumber.strip()
        return None
    except Exception as e:
        print(f"Error getting disk serial: {e}")
        return None

 
def getnodescount(dbhelper):
    sql="SELECT count(*) as count FROM node_heart  WHERE  TIMESTAMPDIFF(MINUTE, opdate, NOW()) <= 20 "
    result=  dbhelper.query(sql)  
    if result is None:
        return 0
    else:
        return result[0]['count']
def getnodeorder(dbhelper,diskid):
    print('getnodeorder',diskid)
    sql=f"SELECT diskid,opdate FROM node_heart WHERE  TIMESTAMPDIFF(MINUTE, opdate, NOW()) <= 20   order by opdate"  
    result = dbhelper.query(sql)
    if result is None:
        return 0
    for index,row in enumerate(result):
        if row['diskid']==diskid:
            return index
    return 0
def getkeywords_test (dbhelper,diskid):
    count=getnodescount(dbhelper)
    order=getnodeorder(dbhelper,diskid)
    sql=f"SELECT keywords   ,ebay,ali FROM sku_keywords   "  
    if count>1:
        sql=sql + f" where mod(id,{count})={order}"  
    print(count,'->',order,'->',sql)
    
    result = dbhelper.query(sql)
    print(len(result))
    return result

def heartnode(dbhelper, diskid):
    try:
        sql = """
        INSERT INTO node_heart (diskid, opdate)
        VALUES (:diskid, now())
        ON DUPLICATE KEY UPDATE opdate = now()
        """
        dbhelper.updatesql(sql, {'diskid': diskid})
        return True       
    except Exception as e:
        print(f"心跳更新失败: {e}")
        traceback.print_exc()
        error_details = traceback.format_exc()
        logging.error(f"心跳更新失败: {error_details}")
        return False


if __name__ == "__main__":
     
    diskid=get_disk_serial_simple()
    print(diskid)
    # conn=getconn(pool)
    dbhelper=MySQLHelper_xue()
    dbhelper.connect()
    heartnode(dbhelper,diskid)
    nodeorder=getnodeorder(dbhelper,'testnode')
    print('节点顺序test',nodeorder)

    nodeorder=getnodeorder(dbhelper,diskid)

    print('节点顺序',diskid,nodeorder)
    count=getnodescount(dbhelper)   
    print('节点数量',count)

    # getkeywords_test(conn,diskid)
    # print('*' * 50)
    # print('*' * 50)
    # getkeywords_test(conn,'testnode')
     